package com.lzx.adx.report.controller.v1.soul;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.model.soul.SoulRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import com.lzx.adx.report.util.helper.KkHeper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 产品：58同城（有道接口）
 * 媒体：趣头条
 */
@RequestMapping("/soul/yd")
@RestController
@Slf4j
public class SoulYouDaoController {


    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;


    @GetMapping("/ios/report")
    public ResponseEntity report(SoulRequest requestParams, HttpServletRequest request) {
        log.info("接收到soul到有道的点击请求参数为{}", JsonUtils.toJsonString(requestParams));
        //1.收到监测的数据存储
        ReportDTO reportDTO = reportMapper.toReportDTO(requestParams);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(requestParams));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis() / 1000));
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });
        String idfa = requestParams.getIdfa();
        reportDTO.setIdfa(idfa);
        if (StringUtils.isNotBlank(idfa)){
            reportDTO.setIdfaSum(SecureUtil.md5(idfa));
        }
        //使用oaid字段用作caid
        reportDTO.setOaid(requestParams.getCaid());
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(requestParams.getDspId());
        //转换产品侧需要url数据
        String finalUrl = KkHeper.covertSoulYouDaoIosUrl(accountDTO, reportDTO);
        log.info("账号为{}完整的soul到有道ios请求地址为{}", requestParams.getDspId(), finalUrl);
        //2.2调用58上报接口
        String body = HttpUtil.createGet(finalUrl).execute().body();
        log.info("账号为{}完整的soul到有道ios响应的结果为{}", requestParams.getDspId(), body);
        return ResponseEntity.ok(new Result());
    }


    /**
     * 58同城的回传
     *
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("/jxydt/callback")
    public ResponseEntity jxydtCallBackUrl(String requestId, String conv_action) {
        log.info("soul收到驾校一点通-IOS回调信息，请求流水号{},回调类型为{}", requestId, conv_action);
        if (StringUtils.isBlank(requestId) || StringUtils.isBlank(conv_action)) {
            log.info("soul收到驾校一点通-IOS回调信息参数异常");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        String currentTimeMillis = String.valueOf(System.currentTimeMillis());

        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
        } else {
            log.error("当前流水号{}，系统当前不存在", requestId);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);
        String transformType = jsonObject.getString(conv_action);
        if (StringUtils.isBlank(transformType)) {
            log.info("soul收到驾校一点通-IOS回调信息当前流水号：{}，事件类型{}不合法，不做数据回传", requestId, conv_action);
            return ResponseEntity.ok(new Result());
        }
        reportDTO.setResultType(conv_action);
        reportDTO.setResultTime(currentTimeMillis);
        reportDTO.setUpdateTime(new Date());
        reportService.updateData(reportDTO,conv_action);
        //3，获取回传地址，进行解码
        String decodeUrl = URLEncoderDecoderTool.decodeURL(reportDTO.getCallback());
        //对数据做替换
        String replaceUrl = decodeUrl.replace("__EVENTTYPE__", transformType).replace("__EVENTTS__", currentTimeMillis);

        log.info("账号{}请求流水号{}驾校一点通-IOS回调soul的完整地址为：{}", reportDTO.getDspId(), requestId, replaceUrl);
        String result = HttpUtil.get(replaceUrl);
        log.info("账号{}请求流水号{}驾校一点通-IOS回调soul的结果为：{}", reportDTO.getDspId(), requestId, result);
        return ResponseEntity.ok(new Result());
    }


}
